<template>
  <div>
    <!-- 筛选条件 -->
    <el-form
      ref="srarchForm"
      :inline="true"
      :model="searchMap"
      class="demo-form-inline"
      style="margin-top:20px;"
    >
      <!-- 重置要看el-form-item组件元素的prop属性上是否指定了字段名，重置才能生效 -->
      <el-form-item prop="cardNum">
        <el-input v-model="searchMap.cardNum" placeholder="会员卡号"></el-input>
      </el-form-item>
      <el-form-item prop="name">
        <el-input v-model="searchMap.name" placeholder="会员名称"></el-input>
      </el-form-item>
      <el-form-item prop="payType" class="payType-input">
        <el-select v-model="searchMap.payType" placeholder="支付类型">
          <el-option
            v-for="option in paytypeOptions"
            :key="option.type"
            :label="option.name"
            :value="option.type"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="birthday">
        <!-- value-format绑定指定格式的日期 -->
        <el-date-picker
          value-format="yyyy-MM-dd"
          v-model="searchMap.birthday"
          type="date"
          placeholder="出生日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" round @click="fetchData" icon="el-icon-search" size="small">查询</el-button>
        <el-button type="primary" round @click="handleAdd" icon="el-icon-edit" size="small">增加</el-button>
        <el-button type="info" round plain @click="resetForm('srarchForm')" size="small">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格数据展示 -->
    <el-table :data="memberList" height="420" style="width: 100%">
      <el-table-column prop="index" label="序号" type="index" width="60"></el-table-column>
      <el-table-column prop="cardNum" label="会员卡号"></el-table-column>
      <el-table-column prop="name" label="会员姓名" width="90"></el-table-column>
      <el-table-column prop="birthday" label="会员生日"></el-table-column>
      <el-table-column prop="phone" label="手机号码"></el-table-column>
      <el-table-column prop="integral" label="可用积分"></el-table-column>
      <el-table-column prop="money" label="开卡金额"></el-table-column>
      <el-table-column prop="payType" label="支付类型">
        <template slot-scope="scope">
          <!--对支付类型进行过滤器特殊处理-->
          <span>{{scope.row.payType | payTypeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="会员地址"></el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!-- 弹出新增窗口 
        title 窗口的标题
        :visible.sync 当它true的时候，窗口会被弹出
    -->
    <el-dialog title="会员编辑" :visible.sync="dialogFormVisible" width="500px">
      <el-form
        :rules="rules"
        ref="pojoForm"
        label-width="100px"
        label-position="right"
        style="width: 400px;"
        :model="pojo"
      >
        <el-form-item label="会员卡号" prop="cardNum">
          <el-input v-model="pojo.cardNum"></el-input>
        </el-form-item>
        <el-form-item label="会员姓名" prop="name">
          <el-input v-model="pojo.name"></el-input>
        </el-form-item>
        <el-form-item label="会员生日" prop="birthday">
          <!-- value-format 是指定绑定值的格式 -->
          <el-date-picker
            style="width: 200px"
            value-format="yyyy-MM-dd"
            v-model="pojo.birthday"
            type="date"
            placeholder="会员生日"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="pojo.phone"></el-input>
        </el-form-item>
        <el-form-item label="开卡金额" prop="money">
          <el-input v-model="pojo.money"></el-input>
        </el-form-item>
        <el-form-item label="可用积分" prop="integral">
          <el-input v-model="pojo.integral"></el-input>
        </el-form-item>
        <el-form-item label="支付类型" prop="payType">
          <el-select v-model="pojo.payType" placeholder="支付类型" style="width: 110px">
            <!-- 不要忘记 payTypeOptions 绑定到data中 -->
            <el-option
              v-for="option in paytypeOptions"
              :key="option.type"
              :label="option.name"
              :value="option.type"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="会员地址" prop="address">
          <el-input type="textarea" v-model="pojo.address"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <!-- <el-button type="primary" @click="addData('pojoForm')">确 定</el-button> -->
        <!-- 通过判断有没有id值来确定点击的是新增窗口还是编辑窗口的确定按钮，来触发不同的方法 -->
        <el-button
          type="primary"
          @click="pojo.id ===null ? addData('pojoForm'):updateDate('pojoForm')"
        >确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { memberTableHead, paytypeOptions } from "@/utils/constData";
import memberApi from "@/api/member.js";
export default {
  data() {
    return {
      memberList: [],
      tableHead: [],
      total: 0, //总记录数
      currentPage: 1, //当前页
      pageSize: 20, //每页显示的条数
      searchMap: {
        cardNum: "",
        name: "",
        payType: "",
        birthday: ""
      }, //条件查询绑定值-------条件值(必须得指定，否则重置会失效)
      paytypeOptions, //要将全局的paytypeOptions绑定到这个实例对象中，等价于paytypeOptions：paytypeOptions
      dialogFormVisible: false, //控制对话框
      pojo: {
        //弹出对话框提交的数据
        id: null,
        cardNum: "",
        name: "",
        birthday: "",
        phone: "",
        money: 0,
        integral: 0,
        payType: "",
        address: ""
      },
      rules: {
        //校验规则
        cardNum: {
          required: true,
          message: "卡号不能为空",
          trigger: "blur"
        },
        name: {
          required: true,
          message: "姓名不能为空",
          trigger: "blur"
        },
        payType: {
          required: true,
          message: "支付类型不能为空",
          trigger: "blur"
        }
      }
    };
  },
  created() {
    //初始化表头
    // this.tableHead = memberTableHead;
    //初始化列表数据
    this.fetchData();
  },
  methods: {
    fetchData() {
      //   memberApi.getmemberList().then(response => {
      //     const memList = response;
      //     console.log(memList.data);
      //     this.memberList = memList.data;
      //   });
      //调用分页查询数据
      memberApi
        .search(this.currentPage, this.pageSize, this.searchMap)
        .then(response => {
          const memList = response.data;
          console.log(memList.rows);
          this.total = memList.total;
          this.memberList = memList.rows;
        });
    },
    //表格编辑按钮-------------
    handleEdit(index, row) {
      console.log(row.id);
      memberApi.getById(row.id).then(response => {
        const rowdata = response;
        if (rowdata.flag) {
          //打开新窗口
          this.dialogFormVisible = true;
          this.pojo = rowdata.data; //因为是双向数据绑定，所以直接赋值给pojo，表单会自动进行数据填充
        } else {
          //新增失败
          this.$message({
            message: "查询失败!",
            type: "warning"
          });
        }
      });
    },
    //表格删除按钮-------------
    handleDelete(index, row) {
      console.log(index, row);
      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          memberApi.deleteById(row.id).then(response => {
            const rowdata = response;
              this.$message({
                type: rowdata.flag?"success":"error",
                message: rowdata.flag?"删除成功!":"删除失败!",
              });
          });
        })
        .catch(() => {});
    },
    //分页改变进行数据更新-
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.fetchData(this.currentPage, this.pageSize, this.searchMap);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.fetchData(this.currentPage, this.pageSize, this.searchMap);
    },
    //点击重置按钮，将输入框清空
    resetForm(formName) {
      //重置要看el-form-item组件元素的prop属性上是否指定了字段名，重置才能生效
      this.$refs[formName].resetFields();
    },
    //点击新增的确定按钮触发事件=-----------------提交表单
    addData(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(this.pojo);
          //提交表单-------------将获取到的表单数据传递给后台  this.pojo  表单自动向这个对象添加数据
          memberApi.add(this.pojo).then(response => {
            const formdata = response;
            if (formdata.flag) {
              //新增成功,重新获取列表数据----刷新数据列表
              this.fetchData(this.currentPage, this.pageSize, this.searchMap);
              this.$message({
                message: "添加信息成功!",
                type: "success"
              });
              this.dialogFormVisible = false;
            } else {
              //新增失败
              this.$message({
                message: "添加信息失败!",
                type: "warning"
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    //编辑窗口点击确定方法
    updateDate(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(this.pojo);
          //提交表单-------------将获取到的表单数据传递给后台  this.pojo  表单自动向这个对象添加数据
          memberApi.updateById(this.pojo).then(response => {
            const formdata = response;
            if (formdata.flag) {
              //新增成功,重新获取列表数据----刷新数据列表
              this.fetchData(this.currentPage, this.pageSize, this.searchMap);
              this.$message({
                message: "修改信息成功!",
                type: "success"
              });
              this.dialogFormVisible = false;
            } else {
              //新增失败
              this.$message({
                message: "修改信息失败!",
                type: "warning"
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    //弹出新增窗口
    handleAdd() {
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        //this.$nextTick(() =>{})是一个异步事件,等dom加载完成之后,回调函数才可以执行
        //弹出窗口打开后,需要加载dom,等dom加载完,再进行重置操作--调用resetFields()方法
        //重置要看el-form-item组件元素的prop属性上是否指定了字段名，重置才能生效
        this.$refs["pojoForm"].resetFields();
      });
    }
  },
  filters: {
    //在过滤器中不能引用当前实例this
    //过滤器，将支付类型编码转换成相应的文字
    payTypeFilter(type) {
      // paytypeOptions.find(obj =>{
      //     if(obj.type === type){
      //         return obj.name;
      //     }
      // })
      const payObj = paytypeOptions.find(obj => obj.type === type);
      return payObj ? payObj.name : null;
    }
  }
};
</script>
<style  scoped>
.payType-input {
  width: 120px;
}
.dialog-input {
  float: left;
  width: 325px;
}
</style>